﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

using System.IO;

namespace TurnLedWithCard
{
public partial class Form1 : Form
{
    private delegate void SetTextDeleg(string data);
    public Form1()
    {
        InitializeComponent();
        SettingRS232();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
    SerialPort mySerialPort = new SerialPort("COM3");
     public void SettingRS232() {
          try {
              
            mySerialPort.BaudRate = 9600; 
            mySerialPort.Parity = Parity.None; 
            mySerialPort.StopBits = StopBits.One; 
            mySerialPort.DataBits = 8; 
            mySerialPort.Handshake = Handshake.None; 
            mySerialPort.ReadTimeout = 2000; 
            mySerialPort.WriteTimeout = 500;
            mySerialPort.DtrEnable = true;
            mySerialPort.RtsEnable = true;

            mySerialPort.Open(); //
              //mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); 
              mySerialPort.DataReceived += DataReceivedHandler;
            textBox1.Text = "Serial Port is Ready.\n";
    } catch (Exception ex) {
              textBox1.Text = ex.Message;
            }
    } 


    static string indata; 
    public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) {
            SerialPort sp = (SerialPort)sender; 
            System.Threading.Thread.Sleep(500);
    // textBox1.Text += sp.ReadLine(); 
        indata = sp.ReadExisting();
            this.BeginInvoke(new SetTextDeleg(DisplayToUI), new object[] { indata });
            //MessageBox.Show(indata); //textBox1.Text += indata.ToString();
           //Input(indata);
    }
    static String UID;
    private void Input(String a)
    {
        UID = a.Replace("\r\n", "");
        //MessageBox.Show(b);
        
           Txt_uid.Text = UID;
        

    //  while(true)  
        KiemTra();
        
    }
    private void KiemTra()
    {
        int a = 0;
        String path = "data.txt";
        name_nv.Text = "";
        try
        {
            FileStream file = new FileStream(path, FileMode.OpenOrCreate);

            StreamReader read = new StreamReader(file);
            while (read.Peek() >= 0)
            {
                String uid = read.ReadLine();
                uid = EncryptDecrypt(uid);
                //MessageBox.Show("dang tim");

                if (uid.IndexOf(UID) >=0)
                {
                    // MessageBox.Show("Tim Thay");
                    name_nv.Text = uid.Replace(UID + ":", "");
                    a = 1;
                    Output();
                    //return 1;
                }
              
             }
                  if (a==0)
                {
                    //MessageBox.Show("không tồn tại ID này");
                    if (UID != null)
                    {
                        String path2 = "Log.txt";

                        FileStream file2 = new FileStream(path2, FileMode.Append);

                        StreamWriter sWriter = new StreamWriter(file2);//fs là 1 FileStream 
                        sWriter.WriteLine(UID + ":" + DateTime.Now.ToString());

                        sWriter.Close();
                        file.Close();
                    }
            }
            read.Close();
            file.Close();

            a = 0;
        }
        catch { }
        //return 0;
    }
    private void Output()
    {
        
        if (mySerialPort.IsOpen)
        {
            mySerialPort.Write("1");
           // MessageBox.Show("Right");
        }
        else MessageBox.Show("Dong");
    }
    private void DisplayToUI(string displayData) {
                textBox1.Text += displayData.Trim();
                Input(displayData.Trim());
        // textBox1.Text += displayData;
    }

    public static int key = 2014;

    public static string EncryptDecrypt(string textToEncrypt)
    {
        StringBuilder inSb = new StringBuilder(textToEncrypt);
        StringBuilder outSb = new StringBuilder(textToEncrypt.Length);
        char c;
        for (int i = 0; i < textToEncrypt.Length; i++)
        {
            c = inSb[i];
            c = (char)(c ^ key);
            outSb.Append(c);
        }
        return outSb.ToString();
    }   
    private void Nap_Click(object sender, EventArgs e)
    {
        //String key = "Ardruino2014";
        String data = EncryptDecrypt(UID + ":" + name_nv.Text);
        




            if (UID != null)
            {
                String path = "data.txt";

                FileStream file = new FileStream(path, FileMode.Append);

                StreamWriter sWriter = new StreamWriter(file);//fs là 1 FileStream 

                sWriter.WriteLine(data);

                sWriter.Close();
                file.Close();
                //sWriter.Dispose();
                // FileStream fs = new FileStream(path, FileMode.Open);
                // StreamReader rd = new StreamReader(fs, Encoding.Unicode);
                MessageBox.Show("ok");
            }
        
            
        }

    

    
    }




    
}

